package main

import (
	"errors"
	"fmt"
	"os"
	"Go36/article48/common"
	"Go36/article48/common/op"
	"runtime"
	"runtime/pprof"
)

var memProfileRate = 8

func main() {
	filename := "memprofile.out"
	f, err := os.Create(filename)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Create File Error: %v", err)
		return
	}
	defer f.Close()

	startMemProfile()

	if err := common.Execute(op.MemProfile, 10); err != nil {
		fmt.Fprintf(os.Stderr, "execute error: %v\n", err)
		return
	}

	if err := stopMemProfile(f); err != nil {
		fmt.Fprintf(os.Stderr, "memory profile stop error: %v\n", err)
		return
	}
}

func startMemProfile() {
	runtime.MemProfileRate = memProfileRate
}

func stopMemProfile(f *os.File) error {
	if f == nil {
		return errors.New("nil file")
	}
	return pprof.WriteHeapProfile(f)
}